const { createLogger, format, transports } = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');

const logFormat = format.combine(
  format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
  format.errors({ stack: true }),
  format.printf(({ timestamp, level, message, stack }) => {
    if (stack) {
      return `${timestamp} ${level}: ${message}\n${stack}`;
    }
    return `${timestamp} [${level}]: ${message}`;
  })
);

// 配置日志轮转（按时间和大小）
const rotateTransport = new DailyRotateFile({
  filename: `${process.env.LOG_FILENAME || 'main'}_%DATE%.log`,
  datePattern: 'YYYYMMDD',
  maxSize: '20m', // 单个文件最大20MB
  maxFiles: '2d', // 超过1天的日志会被自动删除

  format: logFormat,
});

const logger = createLogger({
  level: 'debug',
  transports: [rotateTransport] // 使用轮转配置替代原File transport
});

if (process.env.NODE_ENV !== 'production') {
  logger.add(new transports.Console({
    level: 'debug',
    format: logFormat
  }));
}

module.exports = { logger };